import 'package:flutter/material.dart';

extension ColorExtension on Color {
  // 创建MaterialColor
  MaterialColor toMaterialColor() {
    List<double> strengths = <double>[.05];
    Map<int, Color> swatch = {};
    final int r = red, g = green, b = blue;

    for (int i = 1; i < 10; i++) {
      strengths.add(0.1 * i);
    }
    for (var strength in strengths) {
      final double ds = 0.5 - strength;
      swatch[(strength * 1000).round()] = Color.fromRGBO(
        r + ((ds < 0 ? r : (255 - r)) * ds).round(),
        g + ((ds < 0 ? g : (255 - g)) * ds).round(),
        b + ((ds < 0 ? b : (255 - b)) * ds).round(),
        1,
      );
    }
    return MaterialColor(value, swatch);
  }

  // 调整亮度
  Color darken([double amount = .1]) {
    assert(amount >= 0 && amount <= 1);
    final hsl = HSLColor.fromColor(this);
    final hslDark = hsl.withLightness((hsl.lightness - amount).clamp(0.0, 1.0));
    return hslDark.toColor();
  }

  Color lighten([double amount = .1]) {
    assert(amount >= 0 && amount <= 1);
    final hsl = HSLColor.fromColor(this);
    final hslLight =
        hsl.withLightness((hsl.lightness + amount).clamp(0.0, 1.0));
    return hslLight.toColor();
  }

  // 转换为十六进制字符串
  String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
      '${alpha.toRadixString(16).padLeft(2, '0')}'
      '${red.toRadixString(16).padLeft(2, '0')}'
      '${green.toRadixString(16).padLeft(2, '0')}'
      '${blue.toRadixString(16).padLeft(2, '0')}';

  // 从十六进制字符串创建Color（静态方法）
  static Color? fromHex(String hexString, {double opacity = 1.0}) {
    try {
      final buffer = StringBuffer();
      final hexColor = hexString.replaceFirst('#', '');

      if (hexColor.length == 6) {
        // 将透明度转换为十六进制并添加到颜色前面
        final alpha = (opacity * 255).round().toRadixString(16).padLeft(2, '0');
        buffer.write(alpha);
        buffer.write(hexColor);
      } else if (hexColor.length == 8) {
        // 如果已经包含透明度，则使用自定义opacity覆盖它
        final existingAlpha = int.parse(hexColor.substring(0, 2), radix: 16);
        final newAlpha =
            (existingAlpha * opacity).round().toRadixString(16).padLeft(2, '0');
        buffer.write(newAlpha);
        buffer.write(hexColor.substring(2));
      } else {
        return null;
      }

      final int? color = int.tryParse(buffer.toString(), radix: 16);
      if (color == null) return null;
      return Color(color);
    } catch (e) {
      return null;
    }
  }
}
